var layer, datas;

layui.use(['jquery', 'layer', 'layedit', 'laytpl'], function () {
    var layer = layui.layer;
    var layedit = layui.layedit;
    var laytpl = layui.laytpl;
    var $ = layui.jquery;
    var temp = $("#pl-template"),
        aid = temp.data("id");
    config.api.comment_data += aid;
    var exit_index = layedit.build('pinglun', {
        tool: ['left', 'image'],
        height: 180
    });

    /*文章点赞按钮*/
    $(".good a").on('click', function (e) {
        var that = $(this);
        if ($(this).parent(".good").hasClass("hover")) {
            layer.msg("您已经点过赞啦！");
        } else {
            var id = temp.data('id');
            request({
                url: config.api.thumbs_up,
                data: {aid: id},
                loading: false,
                success: function (result) {
                    if (result.code === 1) {
                        that.parent(".good").addClass("hover");
                        var dz = $(".allhz"), dz2 = $(".dznumbers");
                        var dznumber = parseInt(dz2.data("dz"));
                        dz2.data("dz", castnum(dznumber + 1)).html("已有" + castnum(dznumber + 1) + "次赞");
                        $(".article-bq .bq-dz font").html(castnum(dznumber + 1) + "次");
                        var all_number = parseInt(dz.data("dz")) + 1;
                        dz.html(all_number);
                    } else {
                        layer.msg("您已经赞过了！");
                        that.parent(".good").addClass("hover");
                    }
                }
            });
        }
    });


    /*获取数据，并且初始化*/
    request({
        url: config.api.comment_data,
        loading: false,
        success: function (data) {
            datas = data;
            resetData(data.data);
        }
    });

    /*发送评论*/
    var ifs = true;
    $(".sendpl").click(function () {
        var that = $(this);
        if (!that.hasClass("disabled")) {
            if (!isLogin()) {
                layer.msg("您还没有登陆！");
            } else if (ifs) {

                var content = layedit.getText(exit_index);
                if (content) {
                    that.html('<i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>');
                    ifs = false;
                    var data = {
                        content: content,
                        aid: aid
                    };
                    request({
                        url: config.api.comment,
                        data: data,
                        loading: false,
                        done: function (result) {

                            if (result.code === 1) {

                                var comment_id = result.data['comment_id'];
                                setTimeout(function () {
                                    ifs = true;
                                    $(document.getElementById('LAY_layedit_1').contentWindow.document.body).html("");
                                    var new_data = [{
                                        'id': comment_id,
                                        "avatar": isLogin(true).avatar,
                                        "nick": isLogin(true).nick,
                                        "time": "刚刚",
                                        "url": '/person/' + isLogin(true).uuid + ".html",
                                        "content": content,
                                        "up": 0,
                                        "reply_count": 0,
                                        "reply": []
                                    }];
                                    laytpl(temp.html()).render(new_data, function (html) {
                                        $("#new-pl .title").after(html);
                                        $("#new-pl").show();
                                        if ($("#hot-pl").css("display") === "none") {
                                            $("#new-pl").addClass("hvs");
                                        }
                                        $("body,html").animate({scrollTop: $("#new-pl li").eq(0).offset().top - 100}, 800);
                                    });
                                    that.html("发布评论");
                                }, 1000);
                            } else {
                                that.attr('disabled', true).html("发布评论");
                            }

                            //layer.msg(result.msg);
                        }
                    });

                } else {
                    layer.msg("请先输入评论内容..");
                }
            }
        } else {
            layer.msg("管理员已禁止评论");
        }
    });


    /*评论列表点赞*/
    $("body").delegate(".li-dz", "click", function (e) {
        var that = $(this);
        if ($(this).hasClass("hover")) {
            layer.msg("您已经为Ta点赞啦！");
        } else {

            var id = that.parents('.li-info').data('id');
            request({
                url: config.api.thumbs_up,
                data: {id: id},
                loading: false,
                success: function (result) {
                    if (result.code === 1) {
                        var numbers = parseInt(that.attr("data-dz")) + 1;
                        that.addClass("hover").attr("data-dz", numbers).html('<i class="iconfont icon-dianzan"></i>赞' + castnum(numbers));
                    } else {
                        layer.msg("您已经赞过啦！");
                        that.addClass("hover")
                    }
                }
            });
        }
    });

    /*评论图片点击后*/
    $(document).on("click", ".li-content img", function (e) {
        window.open($(this).attr("src"), "_blank");
    });

    /*初始化数据方法*/

    function comments_data(data, isHot) {

        if (isHot) {
            data.list['comments'] = data.list['comments_hot']
        }
        var comments = data.list['comments'];
        var comments_reply = data.list['comments_reply'];
        //处理评论数据
        comments.forEach(function (value, i) {
            value.reply = [];
            comments_reply.forEach(function (item, j) {
                if (value.id === item['root_id']) {
                    value.reply.push(item);
                }
            });
        });
        return comments;
    }

    function resetData(data) {
        var comments = comments_data(data);
        var comments_hot = comments_data(data, 1);

        //$(".article-bq .bq-wg font").html(castnum(data.nick));
        // $(".article-bq .bq-dz font").html(castnum(data.good) + "次");
        //$(".athuor-info>a>img").attr("src", data.authorimg);
        //$(".nick h3").html(data.author);
        //$(".bq-zz a").html(data.author).attr("href", data.authorurl);
        //$(".athuor-info>a").attr("href", data.authorurl);
        //$(".nick span").html(data.authorintro);
        // athour.eq(1).attr("href", data.authorurl);
        //$(".dznumbers").html("已有" + castnum(data.good) + "次赞").attr("data-dz", castnum(data.good));
        //$(".bq-plcount font").html(castnum(data.pl) + "次");
        $(".bq-hfcount font").html(castnum(parseInt(data.pl) + parseInt(data.hf)) + "次");

        var numof = $(".data .number span");
        numof.eq(0).html(castnum(data.tgcount));
        numof.eq(1).html(castnum(data.tgsuccess));
        numof.eq(2).html(castnum(data.allgood)).attr("data-dz", data.allgood);
        var athour = $(".athuor-info .btn a");
        data.qq && athour.eq(0).attr("href", "javaScript:lxzz('" + data.qq + "');");

        if (data.pl) {
            $(".plnumber").html(castnum(data.pl) + "条评论，" + castnum(data.hf) + "条回复");
        }


        if (data.allow) {
            $(".sendpl").addClass("disabled");
        }
        /*判断当前是否处于登陆状态*/
        var layedit_iframe = $(".layui-layedit-iframe");
        layedit_iframe.parent().css("position", "relative");

        var user = isLogin('info');
        if (user.status) {

            $(".my-nick").html("<img src='" + user['avatar'] + "' />" + user.nick);
            $(".logineds").show();
            if (data.allow) {
                layedit_iframe.after('<div style="position: absolute; width: 100%; height: calc(100% - 43px ); left: 0; bottom: 0; background: #f9f9f9;"><div class="everyone"> 该文章已被管理员关闭评论 </div></div>');
            }
        } else {
            if (data.allow) {
                layedit_iframe.after('<div style="position: absolute; width: 100%; height: calc(100% - 43px ); left: 0; bottom: 0; background: #f9f9f9;"><div class="everyone"> 该文章已被管理员关闭评论 </div></div>');
            } else {
                layedit_iframe.after('<div class="closepl"><div class="everyone"> 请先<a href="javaScript:openLoginK()">登录</a>后再评论 </div></div>');
            }
        }
        /*评论的写入*/
        var temp_html = $("#pl-template").html();

        if (comments_hot && comments_hot.length > 0) {
            laytpl(temp_html).render(comments_hot, function (html) {
                $("#hot-pl").append(html);
            });
            $("#hot-pl").addClass("hvs").show();
        } else {
            $("#new-pl").addClass("hvs");
        }

        if (comments && comments.length > 0) {
            $("#new-pl").show();

            laytpl(temp_html).render(comments, function (html) {
                $("#new-pl").append(html);
            });

            if (data.pages > 1) {
                $(".showMore").css("display", "block").data("page", 1);
            }
        }
    }

    /* 子评论加载更多 */
    $("body").delegate(".zi-loadmore", "click", function (e) {
        var that = $(this);
        that.parent().find("ul li").each(function (i, e) {
            e.removeAttribute('hidden');
        });
        that.hide();
    });

    /* 父评论加载更多 */
    $("body").delegate(".showMore", "click", function (e) {
        var that = $(this);
        that.html("正在加载中...");
        var temp = $("#pl-template");
        var page = parseInt(that.data("page")), pages = datas.data.pages;
        if (page < pages) {
            request({
                url: config.api.comment_data,
                data: {page: page + 1},
                success: function (result) {
                    that.data('page', ++page);
                    laytpl(temp.html()).render(comments_data(result.data), function (html) {
                        $("#new-pl").append(html);
                        that.html("查看更多评论 ");
                        (page >= pages) && that.html("没有更多了");
                    });
                }
            });

        } else {
            that.html("没有更多了");
        }
        console.log(that.data('page'), pages);
    });
    /* 点击回复按钮 */
    var atext = "";
    $("body").delegate(".huifubtn", "click", function (e) {

        if (datas.data.allow) {
            layer.msg("管理员已禁止评论");
        } else {
            if (isLogin()) {
                if ($(this).html() === "收起") {
                    $(this).html(atext);
                    $(".huifu").remove();
                } else {
                    if ($(".huifu").length > 0) {
                        $(".huifu").parent().find(".huifubtn").html(atext);
                    }
                    atext = $(this).html();
                    $(this).html("收起");
                    $(".huifu").remove();
                    $(this).parent().append('<div class="huifu layui-clear"> <input class="huifu_content" placeholder="输入回复内容"/> <b class="sendhf">回复</b> </div>');
                }
            } else {
                openLoginK();
            }
        }
    });

    /*开始回复按钮*/
    var sendhf = true;
    $("body").delegate(".sendhf", "click", function (e) {
        var that = $(this);
        var content = that.parent().find(".huifu_content").val();
        var comment_id = that.parents('.li-info').data("id");
        var pid = that.parents('.zi-cz').data("id");
        var user = isLogin(true);
        if (content && sendhf) {
            content = content.trim();
            sendhf = false;
            that.html('<i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>');
            request({
                url: config.api.comment,
                data: {content: content, aid: aid, pid: pid, comment_id: comment_id},
                done: function (result) {

                    if (result.code === 1) {

                        var comm_id = result.data['comment_id'];
                        var parents = that.parents(".li-info");
                        var person = "/person/" + user.uuid + ".html", nick = user.nick;
                        var li = '<li> <div class="zi-pl-content"> <a href="' + person + '" target="_blank" class="zi-nick">' + nick + '</a>： ' + content + ' </div> <div class="zi-cz" data-id="' + comm_id + '"> <a class="huifubtn">回复</a> · 刚刚 </div> </li>';
                        /*开始模拟将自己的回复写入网页*/
                        if (that.parents(".li-go").length > 0) {

                            if (parents.find(".zi-pl").length > 0) {
                                parents.find(".zi-pl ul").prepend(li);
                            } else {
                                parents.find(".li-content").after('<div class="zi-pl"><ul>' + li + '</ul></div>');
                            }

                        } else {
                            var clickNick = that.parents(".zi-cz").parent().find(".zi-pl-content .zi-nick").eq(0);
                            parents.find(".zi-pl ul").prepend('<li> <div class="zi-pl-content"><a href="' + person + '" target="_blank" class="zi-nick" style="margin-right:7px;">' + nick + '</a>回复   <a href="' + clickNick.attr("href") + '" target="_blank" class="zi-nick" style="margin-right:7px;">' + clickNick.html() + '</a> ： ' + content + ' </div> <div class="zi-cz" data-id="' + comm_id + '"> <a class="huifubtn">回复</a> · 刚刚 </div> </li>');
                        }

                    }
                    $(".huifu").parent().find(".huifubtn").html(atext);
                    $(".huifu").remove();
                    sendhf = true;
                }
            });
        } else {
            layer.msg("您好像还没有编写回复内容~");
        }
    });


    /*上传图片*/
    $("body").on("click", ".layui-layedit-tool i", function (event) {
        layer.msg("该功能已被禁用！");
        return false;
    });

    /*备用下载按钮*/
    $("body").on("click", ".backdown", function () {
        var urls = $(this).attr("href");
        var pass = $(this).attr("data-pass");
        if (pass) {
            layer.open({
                type: 0,
                shadeClose: true,
                skin: 'atuikeLayerSkin1',
                content: '备用下载密码：<font color="#F30">' + pass + '</font>',
                btn: ['前往下载', '取消'],
                yes: function () {
                    window.open(urls, "_blank");
                }
            });
            return false;
        }
    });
});


function getDateDiff(dateTimeStamp) {
    if (dateTimeStamp !== '刚刚') {
        dateTimeStamp = new Date(dateTimeStamp).getTime();
    }
    var result = 0;
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
        return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
        result = "" + parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
        result = "" + parseInt(minC) + "分钟前";
    } else
        result = "刚刚";
    return result;
}

/* 联系QQ弹出框 */
function lxzz(qq) {
    if (qq) {
        if (qq === "---") {
            layer.open({
                type: 0,
                shadeClose: true,
                skin: 'atuikeLayerSkin1',
                content: '该作者由于违反本站管理规范，已被管理员封禁账号。无法联系',
                btn: ['我知道了']
            });
            return;
        }

        layer.open({
            type: 0,
            shadeClose: true,
            skin: 'atuikeLayerSkin1',
            content: '请不要和作者发生任何<font color="red"> 金钱交易 </font> 注意防范网络诈骗 保护好自己财产！',
            btn: ['继续联系', '取消'],
            yes: function () {
                window.open("http://wpa.qq.com/msgrd?v=3&uin=" + qq + "&site=qq&menu=yes", "_blank");
                layer.closeAll();
            }
        });

    } else {
        layer.open({
            type: 0,
            shadeClose: true,
            skin: 'atuikeLayerSkin1',
            content: '该作者没有填写QQ联系方式，无法联系~',
            btn: ['我知道了']
        });
    }
}